package com.zhou.springsecurityoauth2.service.impl;

import com.zhou.springsecurityoauth2.common.ResponseResult;
import com.zhou.springsecurityoauth2.entity.User;
import com.zhou.springsecurityoauth2.redisconfig.RedisCache;
import com.zhou.springsecurityoauth2.service.LoginServcie;
import com.zhou.springsecurityoauth2.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

/**
 * @author zhou
 * @version 1.0
 * @date 2022/10/8 - 10 - 08 - 14:57
 * @description com.zhou.springsecurityoauth2.service.impl
 */
@Service
@RequiredArgsConstructor
public class LoginServcieImpl implements LoginServcie {
    private final AuthenticationManager authenticationManager;
    private final RedisCache redisCache;
    @Override
    public ResponseResult login(User user) {
       // UsernamePasswordAuthenticationFilter
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
          Authentication authenticate = null;
        try {
            authenticate = authenticationManager.authenticate(authenticationToken);
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        //使用userid生成token
        UserDetailsServiceImpl.LoginUser loginUser = (UserDetailsServiceImpl.LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
        redisCache.setCacheObject("login:"+userId,loginUser);
        //把token响应给前端
        HashMap<String,String> map = new HashMap<>();
        map.put("token",jwt);
        return new ResponseResult(200,"登陆成功",map);
    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsServiceImpl.LoginUser loginUser = (UserDetailsServiceImpl.LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();
        redisCache.deleteObject("login:"+userid);
        return new ResponseResult(200,"退出成功");

    }
}
